<template>
	<view class="goodsView">
		<uni-forms ref = "goodsForm" :model="goodsFormData" :rules="goodsRules" :label-width="100" label-align="right">
			<uni-forms-item label="商品图片">
				<uni-file-picker 
				v-model="goodsFormData.thumb"
				mode="grid"
				file-mediatype="image"
				>	
				</uni-file-picker>
			</uni-forms-item>
				
				
			<uni-forms-item label="商品名称" required name="name">
				<uni-easyinput v-model = "goodsFormData.name" placeholder="请输入商品名称" trim="all"></uni-easyinput>		
			</uni-forms-item>
			
			
			<uni-forms-item label="商品分类" required name="category_id">
				<uni-data-select
				collection="wanshop-mall-categories"
				field="_id as value, name as text"
				v-model="goodsFormData.category_id"
				></uni-data-select>			
			</uni-forms-item>
			
			<uni-forms-item label="商品价格" required name="price">
				<uni-easyinput type="number" v-model = "goodsFormData.price" placeholder="请输入商品价格" trim="both"></uni-easyinput>	
			</uni-forms-item>
			
			<uni-forms-item label="商品原价" >
				<uni-easyinput  type="number" v-model = "goodsFormData.before_price" placeholder="请输入商品原价" trim="all"></uni-easyinput>
			</uni-forms-item>
			
			<uni-forms-item label="商品属性" >
				<u-cell :title="skuTitle" isLink :border="false" @click="clickSelect"></u-cell>
				<view class="skuList">
					<view class="item" v-for="(item,index) in goodsFormData.sku_select" :key="item._id"  @click="clickSelect">
						<view class="left">
							{{item.skuName}}:
						</view>
						<view class="right" >
							{{skuChildren(item.children)}}
						</view>
					</view>
				</view>
			</uni-forms-item>
			
			<uni-forms-item label="商品描述">
				<uni-easyinput  type="textarea" v-model = "goodsFormData.description" placeholder="请输入商品描述" ></uni-easyinput>
			</uni-forms-item>
			
			<view class="btnView">
				<button type="primary" @click="onSubmit">确认提交</button>
			</view>
			</uni-forms>
			
			
			<uni-popup ref="attrWrapPop" type="bottom">
			    <view class="attrWrapper">
			        <view class="head">
			            <view class="title">商品属性</view>
			            <view class="addAttr" @click="clickAddAttr()">+ 添加属性</view>
			        </view>
			        <view class="body">
			            <view class="item" v-for="(item, index) in skuArr" :key="index">
			                <view class="top">
			                    <checkbox :checked="item.checked" @click="changgeCheckbox(index)"></checkbox>
			                    <view class="font">
			                        {{ item.skuName }}
			                    </view>
							</view>
							<view class="btnGroup" v-if="item.checked" >
			                        <view class="btn" 
									:class= "child.checked?'active':''"
									v-for="(child,cIdx) in item.children" :key="cIdx" @click="chickChildBtn(index,cIdx)">
			                            {{ child.name }}
			                        </view>
			                        <view class="btn" @click="clickAddAttr(index)">
			                            <u-icon name="plus"></u-icon>
			                        </view>
			                    </view>
			                </view>
			        </view>
			        <view class="foot">
			            <button type="primary" @click="clickConfirmSelect">提交</button>
			        </view>
			    </view>
			</uni-popup>
			<uni-popup ref="addAttrPop" >
				<uni-popup-dialog mode="input" title="新增" placeholder="请输入新增内容" @confirm="dialogConfirm">  </uni-popup-dialog>
			</uni-popup>
	</view>
</template>

<script>
	const skuCloudObj = uniCloud.importObject("wanshop-mall-sku");
	const goodsCloudObj = uniCloud.importObject("wanshop-mall-goods")
	let goodId;
	export default {
		data() {
			return {
				goodsFormData:{
					thumb:[],
					name:"",
					category_id:null,
					before_price:null,
					price:null,
					sku_select:[],
					description:""
				},
				// parent 代表属性，child代表属性值
				addAttrType:"parent",   
				goodsRules:{
					name:{
						rules:[{
						required:true,
							errorMessage:"请输入产品名称"	
						}
						]
					},
					price:{
						rules:[{
							required:true,
							errorMessage:"请输入价格"	
						}
						]},
					category_id:{
						rules:[{
							required:true,
							errorMessage:"请选择分类"	
						}
						]}
						
					
				},
				
				skuArr:[]	
			};
		},
		onLoad(e){
			this.isManage()
			goodId = e?.id ?? null;
			if(goodId) this.getGoodsOne();
			this.getSkuDate();
		},
		
		computed:{
			skuTitle(){
				if(this.goodsFormData.sku_select.length){
					let arr = this.goodsFormData.sku_select.map(item =>{
						return item.skuName
					})
					return arr.join("/")
				}else{
					return"点击添加属性"
				}
			}
		},
		methods:{
			// 获取一个商品
			async getGoodsOne(){
				console.log(goodId);
				let res = await goodsCloudObj.getOne(goodId)
				this.goodsFormData = res.data[0]
				console.log(res);
			},
			
			
			// 属性返回子元素
			skuChildren(arr){
				let nsArr= arr.map(item =>{
					return item.name
				})
				return nsArr.join("/")
			},
			
			// 属性选择弹窗确认
			clickConfirmSelect(){
				let arr=this.skuArr.filter(item =>{
					let state = item.children.some(child => child.checked)
					return item.checked == true && state
				}).map(item=>{
					let children = item.children.filter(child =>{
						return child.checked == true
					})
					return{
						...item,
						children
					}
				})
				console.log(arr);
				this.goodsFormData.sku_select = arr
				this.$refs.attrWrapPop.close();
			},
			// 获取sku列表
			async getSkuDate(){
				let res = await skuCloudObj.get()
				console.log(res);
				this.skuArr = res.data
			},
			// 点击添加属性
			clickAddAttr(index = null){
				if(index === null){
					this.addAttrType = "parent"
					this.attrIndex = null
				}else{
					this.addAttrType = "child"
					this.attrIndex = index;
					console.log(this.attrIndex);
				}
				this.$refs.addAttrPop.open();
			},
			// 添加属性弹窗确认按钮
			async dialogConfirm(e){
				let adde = e.trim();
				if(!adde) return;
				if(this.addAttrType == "parent"){
					let obj = {
						skuName:adde,
						checked:true,
						children:[]
								}
								
					let res = await skuCloudObj.add(obj)
					obj._id = res.id;
					
					this.skuArr.push(obj)
							// 	this.skuArr.push({
							// 	skuName:adde,
							// 	checked:true,
							// 	children:[]
							// })
				}else if(this.addAttrType==="child"){
						console.log(this.attrIndex);
						
						let obj = {
							name:adde,
							checked:true
							
						}
						let id = this.skuArr[this.attrIndex]._id
						console.log(id);
						let res = await skuCloudObj.updateChild(id,obj)
						console.log(res);
						this.skuArr[this.attrIndex].children.push(obj)
							}
						}, 
			changgeCheckbox(index){
				this.skuArr[index].checked = !this.skuArr[index].checked
			},
			// 点击属性的子元素
			chickChildBtn(index,cIdx){
				this.skuArr[index].children[cIdx].checked = !this.skuArr[index].children[cIdx].checked
			},
			// 点击属性选择
			clickSelect(){
				this.skuArr.forEach(item => {
				            item.checked = false;
				            if (item.children) {
				                item.children.forEach(child => {
				                    child.checked = false;
				                });
				            }
				        });
				this.$refs.attrWrapPop.open();
				this.arrSetCheck(this.skuArr,this.goodsFormData.sku_select,"_id")
			},
			
			arrSetCheck(arr1,arr2,key){
				arr1.forEach(item =>{
					arr2.forEach(row =>{
						if(item[key] == row[key]){
							item.checked = true
							if(item.children && item.children.length > 0)
							this.arrSetCheck(item.children,row.children,"name")
						}
					})
				})
			},
			onSubmit(){
				this.$refs.goodsForm.validate().then(res =>{
					this.toDataBase();
					console.log(this.goodsFormData);
				}).catch((err)=>{
					console.log("输入有误：",err);
				})
			},
			async toDataBase(){
				this.goodsFormData.thumb =this.goodsFormData.thumb.map(item =>{
					return{
						url:item.url,
						name:item.name,
						extname:item.extname
					}
				})
				let toastTitle;
				if(goodId){
					toastTitle = "修改成功"
					let res = await goodsCloudObj.update(this.goodsFormData)
				}else{
					toastTitle = "新增成功"
					let res = await goodsCloudObj.add(this.goodsFormData)
				
				}
				uni.showToast({
					title:toastTitle,
					icon:"success"
				})
				setTimeout(()=>{
					uni.navigateBack()
				},1500)
			}
		}
	}
</script>

<style lang="scss" scoped>
.goodsView{
	padding: 30rpx;
	.skuList{
		.item{
			padding: 30rpx;
			background:$page-bg-color;
			margin: 15rpx 0 ;
			@include flex-box-set(start);
		}
	}
}
.attrWrapper{
	padding: 30rpx;
	background: #fff;
	border-radius: 20rpx 20rpx 0 0;
	.head{
		@include flex-box();
		font-size: 34rpx;
		margin-bottom: 30rpx;
		.title{
			font-weight: bold;
		}
		.addAttr{
			color: $brand-theme-color-aux;
		}
	}
	.body{
		.item{
			border-top:1rpx solid $border-color-light;
			&:last-child{
				border-bottom: 1rpx solid $border-color-light;
			}
			.top{
				@include flex-box-set(start);
				padding: 30rpx 0;
				.font{
					padding-left: 10rpx;
					font-weight: bold;
				}
			}
			.btnGroup{
				padding: 10rpx 0 30rpx;
				@include flex-box-set(start);
				flex-wrap: wrap;
				.btn{
					padding: 0rpx 25rpx;
					height: 60rpx;
					border: 1rpx solid $border-color-light;
					margin-right: 20rpx;
					border-radius: 10rpx;
					color: $text-font-color-2;
					margin-bottom: 20rpx;
					@include flex-box-set();
					&.active{
						border-color: $brand-theme-color;
						color: $brand-theme-color;
						background:rgba(236, 87, 79, 0.1);
					}
				}
			}
		}
	}
	.foot{
	padding: 50rpx 200rpx;	
	}
}

</style>
